package com.itheima.hibernate.demo1;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;

import com.itheima.hibernate.domain.Customer;
import com.itheima.hibernate.utils.HibernateUtils;

/**
 * Hibernate的其他的API
 * @author unicorn
 * @version v1.0
 * @createTime 2019年2月23日 下午7:39:16
 */
public class HibernateDemo4 {

	@SuppressWarnings("unchecked")
	@Test
	// Query
	public void demo1() {
		Session session = HibernateUtils.getCurrentSession();
		Transaction tx = session.beginTransaction();
		
		// 通过Session获得Query接口
		// 简单查询
//		String hql = "from Customer";
		// 条件查询
//		String hql = "from Customer where cust_name like ?";
		
		// 分页查询
		String hql = "from Customer";
		Query query = session.createQuery(hql);
		// 设置条件
//		query.setParameter(0, "%梦");
		
		// 设置分页
		query.setFirstResult(3);
		query.setMaxResults(3);
		
		List<Customer> list = query.list();
		for (Customer customer : list) {
			System.out.println(customer);
		}
		
		tx.commit();
	}
	
	@SuppressWarnings("unchecked")
	@Test
	// Criteria QBC(query by criteria)
	public void demo2() {
		Session session = HibernateUtils.getCurrentSession();
		Transaction tx = session.beginTransaction();
		
		// 通过Session获得Criteria的对象
//		Criteria criteria = session.createCriteria(Customer.class);
//		List<Customer> list = criteria.list();
		
		// 条件查询
//		Criteria criteria = session.createCriteria(Customer.class);
//		criteria.add(Restrictions.like("cust_name", "如%"));
		// 分页查询
		Criteria criteria = session.createCriteria(Customer.class);
		criteria.setFirstResult(0);
		criteria.setMaxResults(3);
		List<Customer> list = criteria.list();
		
		for (Customer customer : list) {
			System.out.println(customer);
		}
		
		tx.commit();
	}
	
}
